import {
  Button,
  DatePicker,
  Input,
  Popconfirm,
  message,
  Form,
  Modal,
  Radio,
  Select,
  Row,
  Col,
} from "antd";
import FormItem from "antd/lib/form/FormItem";
import { connect } from "dva";
import moment from "moment";
import React from "react";
import styles from "./index.less";
import MyFormItem from "./components/myFormItem/index"
// const createForm = Form.create;
const { Option } = Select;
const { RangePicker } = DatePicker;
const RadioGroup = Radio.Group;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 5 },
  },
  wrapperCol: {
    xs: { span: 24 },   
    sm: { span: 16 },
  },
  colon: false
};

const _tempKey={
  columnName: undefined, // 字段对应数据库列名
  columnType: undefined, // 字段类型
  filter: undefined, // 筛选条件：1-文本包含 2-文本不包含 3-文本为 4-开头为 5-结尾为 6-大于 7-介于 8-小于 9-包含 10-不包含 11-开始日期 12-结束日期
  startVal: undefined,
  endVal: undefined,
  filterType: '1' // 筛选关系：1-与 2-或 默认为与关系
}

@connect(state => ({
  theme: state.theme,
  currentUser: state.user.currentUser,
  menu: state.menu,
}))
// @createForm({})
// @Form.create()
export default class SearchAdtionalModal extends React.PureComponent {
  formRef = React.createRef();
  state = {
    show: false,
    SearchAdtionalOptions: [],
    columns: [ // 数据层，组件自持
      // {
      //   column: 'series_name', // 字段对应数据库列名
      //   columnType: undefined, // 字段类型
      //   filter: undefined, // 筛选条件：1-文本包含 2-文本不包含 3-文本为 4-开头为 5-结尾为 6-大于 7-介于 8-小于 9-包含 10-不包含 11-开始日期 12-结束日期
      //   startVal: undefined,
      //   endVal: undefined,
      //   filterType: '1' // 筛选关系：1-与 2-或 (第一个无值) 默认为1
      // },
    ],
    dates: [],
    dateDisable: true, // 具体日期是否可以选择
    tempColumns: [],
  };



 
  componentDidMount() {
    console.log('state', this.props)
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }
  setStateData = ({ ...data }) => {
    this.setState({ ...data })
  };
  setFiled = (totalPeriodType, rangeTime) =>{
    this.formRef?.current?.setFieldsValue({
      totalPeriodType: totalPeriodType,
      rangeTime: rangeTime,
    })
  }
  onRadioChange = (info) => {
    this.formRef?.current?.resetFields(["rangeTime"]);
    if (info && info.target) {
      if (info.target.value === 0) {
        this.setState({
          dateDisable: false,
        });
      } else {
        this.setState({
          dateDisable: true,
        });
      }
    }
  };

  checkRangeType = (rule, value, callback) => {
    const rangeType =  this.formRef?.current?.getFieldValue("totalPeriodType");
    if (rangeType === 0 && !value) {
      callback("请输入统计周期具体日期！");
      return;
    }
    callback();
  };
  disabledDate = (current) => {
    const { dates } = this.state;
    if (dates && dates.length > 0) {
      const tooLate = dates[0] && current.diff(dates[0], "days") > 31;
      const tooEarly = dates[1] && dates[1].diff(current, "days") > 31;
      return (
        (current &&
          current < moment().add(-1, "years").add(-1, "days").endOf("day")) ||
        current > moment().add(-1, "days").endOf("day") ||
        tooLate ||
        tooEarly
      );
    }
    return (
      (current &&
        current < moment().add(-1, "years").add(-1, "days").endOf("day")) ||
      current > moment().add(-1, "days").endOf("day")
    );
  };
  onOpenChange = (open) => {
    if (open) {
      this.setState({ dates: [] });
    }
  };

  onCalendarChange = (dates) => {
    this.setState({ dates });
  };

  handleAdd = () => {
    if (this.verificatColumns(this.state.columns)) {
      this.setState({
        columns: this.state.columns.concat([_tempKey]),
      })
    } else {
      message.warning('请完成表单后再添加')
    }
  }

  verificatColumns = (columns) => {
    let isOk = true
    columns.map(i => {
      !i.columnName && (isOk = false);
      !i.columnType && (isOk = false);
      !i.filter && (isOk = false);
      (
        i.startVal === undefined ||
        i.startVal === null ||
        i.startVal === ""
      ) && (isOk = false);
      !i.filterType && (isOk = false);
      return i;
    });
    return isOk;
  }

  handleSubmit = (msg) => {
    const {handleSubmit,getStatisticalCycle} = this.props;
    if (!this.verificatColumns(this.state.columns)) {
      message.warning('请设置完整的筛选选项')
      return;
    }
    handleSubmit && handleSubmit(this.state.columns);
    // const {  form } = this.props;
    getStatisticalCycle && (this.formRef.current && this.formRef.current.validateFields().then((values) => {
      console.log('formvalues', values);
      getStatisticalCycle(values);
    })
    )
    this.modalHide();
  }
  useCommonUse = () => {
    console.log('this.state.SearchAdtionalOptionsxxxxxxx', this.state.SearchAdtionalOptions)
    const _SearchAdtionalOptions = this.state.SearchAdtionalOptions.map(i => ({
      ...i,
      disabled: this.state.tempColumns.some(j => {
        return j.columnName == i.columnName;
      })
    }));
    this.setState({
      SearchAdtionalOptions: _SearchAdtionalOptions,
      columns: this.state.tempColumns
    })
  }
  setCommonUse  = () => {
    // const {currentUser: {userName}} = this.props;
    const { menu : { userProfile } } = this.props;
    if (!this.verificatColumns(this.state.columns)) {
      message.warning('请完成表单后再进行保存')
      return;
    }
    const data = JSON.parse(localStorage.getItem("creditData"));
    const id = `${this.props.fieldName}searchAdtional_${userProfile.merchant1Id}_${userProfile.accountName}`;
   //首先进入页面需要先判断是否存在localData
   if (data) {
    data[id] = JSON.stringify(this.state.columns);
   localStorage.setItem("creditData", JSON.stringify(data));
    }else{
     const creditData ={};
     creditData[id] = JSON.stringify(this.state.columns);
     localStorage.setItem("creditData", JSON.stringify(creditData));
  }
    //localStorage.setItem(`${this.props.fieldName}searchAdtional_${userProfile.merchant1Id}_${userProfile.accountName}` , JSON.stringify(this.state.columns));
    this.setState({
      tempColumns: this.state.columns
    })
    message.success('保存成功')
  }
  reset = (callback) => {
    const { form } = this.props;
    const {getStatisticalCycle} = this.props;
    const _SearchAdtionalOptions = this.state.SearchAdtionalOptions.map(i => {
      return {
        ...i,
        disabled: false
      }
    });
    console.log(_SearchAdtionalOptions);
    this.setState({
      SearchAdtionalOptions: _SearchAdtionalOptions,
      columns: [_tempKey]
    }, () => {
      getStatisticalCycle && (
        // this.formRef?.current?.setFieldsValue({
        //   totalPeriodType: 2,
        // })
      this.handleFormReset()
      )
      if(callback) {callback()};
    })
  }
  handleFormReset = () =>{
        this.formRef.current?.resetFields();
        this.formRef?.current?.setFieldsValue({
          totalPeriodType: 2,
        })
        this.setState({
          dateDisable: true
        })
  }
  getCommonUse= () => {
    const { menu : { userProfile } } = this.props;
    //const columns = localStorage.getItem(`${this.props.fieldName}searchAdtional_${userProfile.merchant1Id}_${userProfile.accountName}`);
    const data = JSON.parse(localStorage.getItem("creditData"));
    const id = `${this.props.fieldName}searchAdtional_${userProfile.merchant1Id}_${userProfile.accountName}`;
    let columns = null;
    if(data){
      columns =  data[id];
      }
    let _c = [];
    console.log(columns);
    let flag = true;
    try {
      _c = JSON.parse(columns)
    } catch (error) {
      // message.warning('没有设置');
      flag = false;
    }
    if (flag) {
      this.setState({
        tempColumns: _c
      })
    }
  }
  modalShow = (specialData, exChangeData) => {
    // 特殊数据
    const _specialData = JSON.parse(JSON.stringify(specialData));
    // 外面带进来的数据
    const _exChangeData = JSON.parse(JSON.stringify(exChangeData)).filter(i => { // 筛选空值
      return !(i.startVal === undefined || i.startVal === null || i.startVal === '');
    });
    // 
    let _columns = JSON.parse(JSON.stringify(this.state.columns));
    // 将可选字段和特殊数据相结合，特殊数据为主
    let _SearchAdtionalOptions =  JSON.parse(JSON.stringify(this.props.SearchAdtionalOptions)).map(i => {
      const columnType = i.type;
      delete i.type;
      return {...i, columnType};
    }).map(i => {
      // console.log(specialData, i);
      const special =  _specialData.find(j => j.columnName == i.column);
      if (special) {
        // console.log(special);
        return {
          ...i,
          ...special,
        };
      }
      return i;
    })
    // 从外面带入的
    const newExChangeData = _exChangeData.map(i => {
      const _c = _SearchAdtionalOptions.find(n => i.columnName == n.column);
      const _o = _columns.find(j => i.columnName == j.columnName);
      return {
        ..._c,
        ..._o,
        ...i
      }
    });
    // 里面的字段
    const otherData = _columns.filter(i => !_exChangeData.some(j => i.columnName == j.columnName)).map(i => {
      const _c = _SearchAdtionalOptions.find(n => i.columnName == n.column);
      return {
        ..._c,
        ...i
      }
    })
    

    const allData = newExChangeData.concat(otherData)
    // 加disable，防止重复字段
    _SearchAdtionalOptions = _SearchAdtionalOptions.map(i => ({
      ...i,
      disabled: allData.some(j => {
        return j.columnName == i.column;
      })
    }));
    this.getCommonUse();
    if (!allData.length) {
      allData.push(_tempKey);
    }
    
    // 赋值
    this.setState({
      show: true,
      SearchAdtionalOptions: _SearchAdtionalOptions,
      columns: allData,
    });
  }
  modalHide = () => {
    this.setState({
      show: false
    })
  }

  render() {
    const {
      submitBntLading,
      columns,
      show,
      SearchAdtionalOptions,
      dateDisable
    } = this.state;
    // const {SearchAdtionalOptions} = this.props;
    // const {
    //   form: { getFieldDecorator },getStatisticalCycle} = this.props;
    const {
     getStatisticalCycle} = this.props;
    return (
      <Modal
        title="新建筛选条件"
        width={900}
        onCancel={() => this.modalHide()}
        visible={show}
        footer={[
          <Popconfirm
            key="reset"
            title={'是否重置更多筛选内的内容？'}
            onConfirm={e => this.reset()}
          >
            <Button>重置</Button>
          </Popconfirm>,
          <Button
            key="back"
            type="ghost"
            onClick={() => this.modalHide()}
          >
            取 消
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={submitBntLading}
            onClick={() => this.handleSubmit("submit")}
          >
            确 定
          </Button>
        ]}
      >
       <div className={styles.wrapper}>
         <div style={{ paddingBottom: "30px" }}>
           {getStatisticalCycle && (
                  <Form ref={this.formRef} layout="vertical">
                    <Row gutter={24}>
                      <Col span={12}>
                      <FormItem key={"totalPeriodType"} label={"统计周期"} name="totalPeriodType">
                          <RadioGroup onChange={this.onRadioChange}>
                            <Radio value={2}>本周</Radio>
                            <Radio value={4}>本月</Radio>
                            <Radio value={5}>上周</Radio>
                            <Radio value={8}>上月</Radio>
                            <Radio value={0}>具体日期</Radio>
                          </RadioGroup>
                      </FormItem>
                      </Col>
                      <Col span={12}> 
                      <div className={styles.rangeInput}>
                      <FormItem key={"rangeTime"} name="rangeTime"
                       rules={[{ validator: this.checkRangeType }]}
                      >
                          <RangePicker
                            disabled={dateDisable}
                            disabledDate={this.disabledDate}
                            placeholder={["开始日期", "结束日期"]}
                            allowClear
                            style={{ width: "100%", marginTop: "40px" }}
                            format="YYYY-MM-DD"
                            onCalendarChange={this.onCalendarChange}
                            onOpenChange={this.onOpenChange}
                            getCalendarContainer={(trigger) =>
                              trigger.parentNode
                            }
                          />
                      </FormItem>
                      </div>
                      </Col>
                  </Row>
              </Form>
          )}
         </div>
        {columns.map((i, index) => {
          return <MyFormItem
            key={`formItem${index}`}
            original={i}
            itemIndex={index}
            onChangeOriginal={ // item向上修改组件的值
              e => {
                const newKeys = Object.assign([], this.state.columns);
                newKeys[index] = {
                  ...i,
                  ...e
                }
                // 如果某个字段被选了，那么这个字段disable掉
                const newSearchAdtionalOptions = SearchAdtionalOptions.map(i => ({
                  ...i,
                  disabled: newKeys.some(j => {
                    return j.columnName == i.column;
                  })
                }))
                // 赋值
                this.setState({
                  columns: newKeys,
                  SearchAdtionalOptions: newSearchAdtionalOptions
                });
              }
            }
            onDel={() => { // 删除
              const newKeys = this.state.columns.filter((j,jindex) => jindex != index);
              // 如果某个字段被选了，那么这个字段disable掉
              const newSearchAdtionalOptions = SearchAdtionalOptions.map(i => ({
                ...i,
                disabled: newKeys.some(j => {
                  return j.columnName == i.column;
                })
              }))
              if (!newKeys.length) {
                newKeys.push(_tempKey)
              }
              this.setState({
                columns: newKeys,
                SearchAdtionalOptions: newSearchAdtionalOptions
              });
            }}
            formItemLayout={formItemLayout} // formitem的样式
            SearchAdtionalOptions={SearchAdtionalOptions} // 能够选择的选项
          ></MyFormItem>
        })}
        <FormItem style={{ paddingLeft: "90px" }}>
          <Button style={{ marginRight: "20px" }} onClick={this.handleAdd} type="primary">新增选项</Button>
          { this.state.tempColumns && this.state.tempColumns.length >0 && (
            <Popconfirm
              title={'是否使用常用筛选？选择常用筛选则会替换当前筛选内容'}
              onConfirm={this.useCommonUse}
            >
              <Button style={{ marginRight: "20px" }}>常用筛选</Button>
            </Popconfirm>
          )}
          { this.state.columns.filter(i => {
            return !(i.startVal === undefined || i.startVal === null || i.startVal === '');
          }).length ? 
          (this.state.tempColumns || []).length ? 
          <Popconfirm
            title={'是否保存？选择保存则会替换之前设置的内容'}
            onConfirm={this.setCommonUse}
          >
            <Button style={{ marginRight: "20px" }}>保存为常用筛选</Button>
          </Popconfirm>: 
          <Button style={{ marginRight: "20px" }} onClick={this.setCommonUse}>保存为常用筛选</Button>: ''}
        </FormItem>
       </div>
      </Modal>
    );
  }
}
